
import GlobalEvent from "../../../cfw/event/GlobalEvent";
import { EventName } from "../../../public/Config";
import CookeryRoomStep from "./CookeryRoomStep";
import CollisionHelper from "../../../cfw/collide/CollisionHelper";
import BagManager from "../../bag/BagManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CookeryRoomStep2 extends CookeryRoomStep {

    @property(cc.Node)
    handle: cc.Node = null;

    @property(cc.Node)
    posNode: cc.Node = null;



    start() {
        this.node.active = true;
        // this.push(x, y, w / 2, h / 2)
        this.handle.on(cc.Node.EventType.TOUCH_START, this.touchStart, this)

    }


    touchCancel() {


    }

    touchStart(e: cc.Touch) {
        let pos = this.handle.convertToNodeSpaceAR(e.getLocation())
        let count = this.handle.childrenCount;
        for (let index = 0; index < count; index++) {
            const element = this.handle.children[index]
            if (CollisionHelper.isPositionInRect(pos, element.getBoundingBox())) {
                this.handle.removeChild(element, false)
                this.node.addChild(element)
                let spos = element.position;
                // let swpos = this.node.convertToNodeSpaceAR(spos)

                element.x = spos.x + this.handle.x;
                element.y = spos.y + this.handle.y;
                cc.log(' swpos ', element.x, element.y, this.handle.x, this.handle.y)
                let tnode = this.posNode.children[index];
                let tpos = tnode.position
                element.angle = tnode.angle;
                this.posNode.removeChild(tnode)
                let tx = tpos.x + this.posNode.x
                let ty = tpos.y + this.posNode.y
                cc.log(' swpos ', tx, ty)
                cc.tween(element).to(0.5, { x: tx, y: ty, scaleX: 0.6, scaleY: 0.6 }).start()
                BagManager.addCoin(10, element.parent.convertToWorldSpaceAR(element.getPosition()))
                break;
            }
        }
        count = this.handle.childrenCount;
        if (count <= 0) {
            this.finish()
        }

    }



    finish() {
        cc.log(' finish == ')
        GlobalEvent.instance().emit(EventName.UPDATE_COOKIE_STEP,2)
    }


}
